(function($) {
    $.fn.emoji = function(method) {
        //初始化emoji data
        $.fn.emoji.initEmojiData();
        // Method calling logic  
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            arguments[0].containerIndex = $(".emojiContainer").length;
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }

    };
    var methods = {
        init: function(options) {
            var defaults = {
                showTab: false,
                width: 200,
                height: 200,
                showIndex: 0,
                triggerBtn: null
            };
            var that = this;
            //绑定事件
            function bindEvent() {
                $($(that).data("options").triggerBtn).on("hover", function() {
                    $(that).data("container").mouseout(function() {
                        if ($(window.event.currentTarget).closest(".emojiContainer").length == 0) {
                            $(that).emoji("hide");
                        }
                    });
                    $(that).emoji("show");
                })
            };
            //在光标处插入表情
            function _insertAtCursor(field, value, selectPastedContent) {
                var sel, range;
                if (field.nodeName === 'DIV') {
                    field.focus();
                    if (window.getSelection) {
                        sel = window.getSelection();
                        if (sel.getRangeAt && sel.rangeCount) {
                            range = sel.getRangeAt(0);
                            range.deleteContents();
                            var el = document.createElement('div');
                            el.innerHTML = value;
                            var frag = document.createDocumentFragment(),
                                node, lastNode;
                            while ((node = el.firstChild)) {
                                lastNode = frag.appendChild(node);
                            }
                            var firstNode = frag.firstChild;
                            range.insertNode(frag);

                            if (lastNode) {
                                range = range.cloneRange();
                                range.setStartAfter(lastNode);
                                if (selectPastedContent) {
                                    range.setStartBefore(firstNode);
                                } else {
                                    range.collapse(true);
                                }
                                sel.removeAllRanges();
                                sel.addRange(range);
                            }
                        }
                    } else if ((sel = document.selection) && sel.type !== 'Control') {
                        var originalRange = sel.createRange();
                        originalRange.collapse(true);
                        sel.createRange().pasteHTML(html);
                        if (selectPastedContent) {
                            range = sel.createRange();
                            range.setEndPoint('StartToStart', originalRange);
                            range.select();
                        }
                    }
                } else {
                    if (document.selection) {
                        field.focus();
                        sel = document.selection.createRange();
                        sel.text = value;
                        sel.select();
                    } else if (field.selectionStart || field.selectionStart === 0) {
                        var startPos = field.selectionStart;
                        var endPos = field.selectionEnd;
                        var restoreTop = field.scrollTop;
                        field.value = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length);
                        if (restoreTop > 0) {
                            field.scrollTop = restoreTop;
                        }
                        field.focus();
                        field.selectionStart = startPos + value.length;
                        field.selectionEnd = startPos + value.length;
                    } else {
                        field.value += value;
                        field.focus();
                    }
                }
            }
            return this.each(function() {
                // 如果存在选项，则合并之 
                if (!options.triggerBtn)
                    throw new Error("请设置按钮！");
                if (options) {
                    $.extend(defaults, options);
                }
                // 其他代码咯 
                var $container = $("#emojiContainer" + defaults.containerIndex);
                if ($container.length == 0) {
                    $container = $('<div class="emojiContainer" style="display: none;"></div>').attr("id", "emojiContainer" + defaults.containerIndex);
                    $("body").append($container);
                }
                $container.css("boxSizing", "");
                $(this).data("options", options).data("container", $container);
                var $tab = $("<ul class='emTab'></ul>");
                var that = this;
                $.each($.fn.emoji.emojiArr, function(i, etype) {
                    if (etype) {
                        var $emojis = $("<ul class='emojiPanel'></ul>").attr("data-type", etype.category).css("display", i == defaults.showIndex ? "block" : "none");
                        $.each(etype.items, function(j, emoji) {
                            var $eImg = $("<img/>").attr("alt", emoji.text).attr("src", $.fn.emoji.emojiImgPath + emoji.src).width(32).height(32);
                            var $item = $("<li/>").attr("title", emoji.text).data("name", emoji.text).append($eImg);
                            $emojis.append($item);
                            $item.click(function(e) {
                                if ($(that).is("div"))
                                    _insertAtCursor(that, methods.parseEmojiToImg($item.data("name")), false);
                                else if ($(that).is(":text,textarea"))
                                    _insertAtCursor(that, $item.data("name"));
                                $container.hide();
                                e.stopPropagation(); //阻止冒泡
                            })
                        })
                        $container.append($emojis);
                        var $type = $("<li/>").attr("tabIndex", i).attr("id", "em_" + etype.category).html(etype.category).appendTo($tab).addClass(i == defaults.showIndex ? "block" : "none");
                        $emojis.perfectScrollbar();
                        $type.click(function() {
                            $container.find("ul.emojiPanel").hide();
                            $container.find("ul.emojiPanel:eq(" + $(this).attr("tabIndex") + ")").show();
                        })
                    };
                })
                if (defaults.showTab) {
                    var $tabContainer = $("<div class='emojiTabContanier'></div>").append($tab);
                    $container.append($tabContainer);
                    $tabContainer.perfectScrollbar();
                }
                bindEvent();
                if ($(this).is("div"))
                    $(this).perfectScrollbar();
                $("*").click(function() {
                    console.log("触发了")
                    var $activeCtrl = $(document.activeElement);
                    if ($activeCtrl.closest(".emojiContainer").length == 0) {
                        $container.fadeOut();
                    }
                })
            });
        },
        //弹出选择层
        show: function() {
            var that = this;
            console.log("position:top-" + $($(that).data("options").triggerBtn).position().top + ",left-" + $($(that).data("options").triggerBtn).position().left)
            console.log("offset:top-" + $($(that).data("options").triggerBtn).offset().top + ",left-" + $($(that).data("options").triggerBtn).offset().left)
            var offtop = $($(that).data("options").triggerBtn).offset().top;
            var offleft = $($(that).data("options").triggerBtn).offset().left;
            $(that).data("container").css({
                position: "absolute",
                top: offtop - $(that).data("container").outerHeight(),
                left: offleft
            }).fadeIn();
            window.event.stopPropagation();
        },
        //隐藏选择层
        hide: function() {
            $(this).data("container").fadeOut();
            window.event.stopPropagation();
        },
        //转换emoji字符串为对应的图片
        parseEmojiToImg: function(emojiStr) {
            return '<img class="emoji_icon" data-name="' + emojiStr + '" src="' + window.emojiData[emojiStr] + '"/>';
        },
        //转换当前内容为Html
        parseToHtml: function() {
            $(this).html($(this).html().replace(/(:[\w]+:)/g, function($0, $1) {
                var n = window.emojiData[$1];
                if (n) {
                    return '<img class="emoji_icon" data-name="' + $1 + '" src="' + n + '"/>';
                }
            }));
        },
        //转换当前html为emoji
        parseToEmoji: function() {
            if ($(this).is("div"))
                return $(this).html().replace(/<img[^>]+data-name\s*=\s*['\"]([:\w:]+)['\"][^>]*>/gi, "$1");
            else if ($(this).is(":text,textarea")) {
                return $(this).val().replace(/<img[^>]+data-name\s*=\s*['\"]([:\w:]+)['\"][^>]*>/gi, "$1");
            }
        }
    }
})(jQuery);